package com.cloud_sang.fubai.controller;

import com.cloud_sang.entity.CommonResult;
import com.cloud_sang.entity.Payment;
import com.cloud_sang.fubai.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassTitle: PaymentController
 * @ProjectName springcould2020
 * @Description:
 * @Author Sangsang
 * @Date 2020/9/9
 * @Time 16:22
 */
@RestController
@Slf4j
@RequestMapping("payment")
public class PaymentController {
	@Resource
	private PaymentService paymentService;

	@Value("${server.port}")
	private String serverPort;

	@Resource
	private DiscoveryClient discoveryClient;


	@GetMapping("get/{id}")
	public CommonResult<Payment> getById(@PathVariable("id") Long id) {
		log.info("*****查询id: " + id);
		log.info("*****端口: " + serverPort);
		return paymentService.getPaymentById(id);
	}

	@PostMapping("create")
	public CommonResult<Payment> create(@RequestBody Payment payment) {
		log.info("*****插入数据: " + payment.toString());
		log.info("*****端口: " + serverPort);

		return paymentService.create(payment);
	}


	@GetMapping(value = "discovery")
	/**
	 * @Description TD: 服务发现Discovery
	 * @param
	 * @Return java.lang.Object
	 * @Author sangsang
	 * @Date 2020/9/9 23:14
	 **/
	public Object discovery() {
		List<String> services = discoveryClient.getServices();
		for (String element : services) {
			log.info("***** element:" + element);
		}
		List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
		for (ServiceInstance instance : instances) {
			log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
		}
		return this.discoveryClient;
	}

	/**
	 * feign超时测试
	 * @return
	 */
	@GetMapping("/feign/timeout")
	public String paymentFeignTimeOut(){
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return serverPort;
	}

}
